<template>
  <div class="workflow-management">
    <!-- 编排管理主界面内容 -->
    <div class="left-menu">
      <h1 class="title">编排管理</h1>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="vertical"
        @select="handleSelect"
      >
        <el-menu-item index="全部分类">全部分类</el-menu-item>
        <el-menu-item
          v-for="option in sceneOptions"
          :key="option.name"
          :index="String(option.name)"
        >
          {{ option.name }}
        </el-menu-item>
      </el-menu>
    </div>
    <div class="right-content">
      <h1>{{ getSelectedMenuText() }}</h1>
      <div class="search-toolbar">
        <div class="select-group">
          <el-select
            v-model="publishStatus"
            placeholder="请选择发布状态"
            @change="handleSearch"
            class="search-input"
          >
            <el-option
              v-for="option in publishStatusOptions"
              :key="option.type"
              :label="option.type"
              :value="option.type"
            ></el-option>
          </el-select>
        </div>
        <div class="action-group">
          <router-link to="/workflow/addWorkflow" class="add-workflow-link">
            <el-button type="primary" :icon="Plus">新增编排</el-button>
          </router-link>
        </div>
      </div>

      <KyTable
        ref="tableRef"
        :getData="getWorkflowList"
        :showSelect="showSelect"
        :showSearchAndSelect="true"
        :showFuzzySearch="true"
        :search_criteria="searchCriteria"
      >
        <template #table-action>
          <div class="os-upgrade-table-action">
            <!-- 设置 -->
            <el-button
              class="ky-item-button"
              @click.stop="handleCustomColumn"
              name="plugin-os-upgrade:operation"
              type="default"
            >
              <el-icon><Setting /></el-icon>
            </el-button>
          </div>
        </template>
        <!-- table表格 -->
        <template #table>
          <el-table-column prop="name" :label="'编排名称'" />
          <el-table-column prop="last_step_num" :label="'任务数'" />
          <el-table-column prop="publish_status" :label="'发布状态'" />
          <el-table-column prop="usage_type" :label="'使用类型'" />
          <el-table-column prop="tag" :label="'场景'" />
          <el-table-column prop="modify_user" :label="'修改人'" />
          <el-table-column prop="modify_time" :label="'修改时间'" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </template>

        <template #empty>
          <div>
            <router-link to="/workflow/addWorkflow">
              <span role="button" class="link-btn"> 创建一个作业吧! </span>
            </router-link>
          </div>
        </template>
      </KyTable>
    </div>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :before-close="handleCloseDialog"
      :width="dialogWidth"
    >
      <CustomColumn
        v-if="rwType === 'custom_list'"
        @click="handleCloseDialog"
        :customData="colData"
        :rawData="rawData"
        @handleOk="handleCustomColumnOk"
      ></CustomColumn>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineAsyncComponent, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { getWorkflowList, workflowStatus, deleteWorkflow } from '@/api/workFlow';
import { tagList } from '@/api/tag';
import { ElMessage, ElMessageBox } from 'element-plus';
const KyTable = defineAsyncComponent(() => import('@/components/KyTable/index.vue'));
const tableRef = ref<InstanceType<typeof KyTable> | null>(null);
const CustomColumn = defineAsyncComponent(() => import('@/components/customColumn/index.vue'));
const dialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('自定义列');
const dialogWidth = ref<string>('50%');
const rwType = ref<string>('custom_list');
const colData = ref<any>([]);
const rawData = ref<any>([]);
const showSelect = ref<boolean>(true);
const activeIndex = ref('全部分类');
const publishStatus = ref('');
const publishStatusOptions = ref<any[]>([]);
// 获取选中的菜单文本
const getSelectedMenuText = () => {
  if (activeIndex.value === '全部分类') {
    return '全部分类';
  }
  const selectedOption = sceneOptions.value.find(
    (option: any) => String(option.name) === activeIndex.value,
  );
  return selectedOption ? selectedOption.name : '';
};
interface SearchCriteria {
  paged: boolean;
  workflowScene: string;
  publishStatus: string;
}

const searchCriteria = ref<SearchCriteria>({
  paged: true,
  workflowScene: '全部分类',
  publishStatus: '',
});

const handleSearch = () => {
  searchCriteria.value = {
    paged: true,
    workflowScene: getSelectedMenuText(),
    publishStatus: publishStatus.value,
  };
};

// 获取场景标签
const sceneOptions: any = ref([]);
const getTagList = async () => {
  const res = await tagList();
  if (res.data.code === 200) {
    sceneOptions.value = res.data.data;
  }
};

// 组件挂载时获取发布状态
const handleSelect = (key: string) => {
  activeIndex.value = key;
  handleSearch();
};
// 删除编排
const handleDelete = async (row: any) => {
  await ElMessageBox.confirm('确定删除选中的编排吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  const res = await deleteWorkflow({ id: [row.id] });
  if (res.data.code === 200) {
    tableRef.value?.refresh();
    ElMessage.success('删除成功');
  } else {
    ElMessage.error(res.data.msg);
  }
};

const handleCustomColumnOk = (val: any) => {
  console.log(val);
  handleCloseDialog();
};
const handleCloseDialog = () => {
  dialogVisible.value = false;
  rwType.value = '';
};
const handleCustomColumn = (row: any) => {
  getCustomColumnFun();
  rwType.value = 'custom_list';
  dialogVisible.value = true;
  dialogTitle.value = '自定义列';
};
const getCustomColumnFun = async () => {
  colData.value = [
    { name: 'name', label: '编排名称', visible: true },
    { name: 'last_step_num', label: '任务数', visible: true },
    { name: 'publish_status', label: '发布状态', visible: true },
    { name: 'modify_user', label: '修改人', visible: true },
    { name: 'modify_time', label: '修改时间', visible: true },
  ];

  // 为rawData设置初始值，确保与colData结构一致
  rawData.value = JSON.parse(JSON.stringify(colData.value));
};

// 获取发布状态枚举
const fetchPublishStatus = async () => {
  const res = await workflowStatus();
  if (res.data.code === 200) {
    publishStatusOptions.value = res.data.data;
  }
};

onMounted(() => {
  fetchPublishStatus();
  getTagList();
});
</script>

<style scoped lang="scss">
.workflow-management {
  display: flex;
}
.left-menu {
  width: 150px;
  .title {
    font-size: 16px;
    height: 40px;
    line-height: 40px;
    text-indent: 5px;
    // color: #57abff;
  }
  .search-input {
    width: 100%;
    padding: 5px;
    margin-top: 10px;
  }
  .el-menu {
    border-right: none;
  }
}
.right-content {
  flex: 1;
  overflow: auto;
  padding-left: 10px;
  border-left: 1px solid #e4e7ed;

  h1 {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 20px;
    padding-bottom: 10px;
    background: #1f2d45;
    color: #fff;
    height: 40px;
    line-height: 40px;
    text-indent: 10px;
  }
}

.search-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.select-group {
  display: flex;
  gap: 12px;
}

.action-group {
  display: flex;
  .add-workflow-link {
    margin-left: 12px;
  }
}

.search-input {
  width: 200px;
}
</style>
